package com.ph.finder.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.event.MapClickHandler;
import com.google.gwt.maps.client.event.MapMoveEndHandler;
import com.google.gwt.maps.client.event.MapZoomEndHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.geom.Point;
import com.google.gwt.maps.client.geom.Size;
import com.google.gwt.maps.client.overlay.Icon;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.InlineHyperlink;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Widget;
import com.ph.finder.client.PrecinctService;
import com.ph.finder.client.PrecinctServiceAsync;

public class PrecinctMapSecondStepPane extends Composite {

	protected static final String ERR_NOT_CLOSE_ENOUGH = "" +
"Zoom In closer to drop the precinct marker better.";

	interface PaneStyle extends CssResource {
		String disabled();
		String enabled();
	}

	private static PrecinctMapSecondStepPaneUiBinder uiBinder = GWT
			.create(PrecinctMapSecondStepPaneUiBinder.class);

//	private final PrecinctMapPage ctr;
	private final String precinctNo;
	private final MapWidget maps;
	private final String province;
	private final String municipality;
	private LatLng mapCenter;
	private double latBound;
	private double lngBound;
	private int mapZoom;
	private Marker precinctMarker;
	private boolean finalizingLocation;

	interface PrecinctMapSecondStepPaneUiBinder extends
			UiBinder<Widget, PrecinctMapSecondStepPane> {
	}

	@UiField
	InlineLabel precinctNoLabel;

	@UiField
	InlineLabel provinceLabel;

	@UiField
	InlineLabel municipalityLabel;

	@UiField
	InlineLabel errorLabel;

	@UiField
	InlineHyperlink mapmakerLink;

	@UiField
	HTMLPanel infoPanel1;

	@UiField
	HTMLPanel infoPanel2;

	@UiField
	Button acceptLocation;

	@UiField
	Anchor editAddress;

	@UiField
	PaneStyle style;

	public PrecinctMapSecondStepPane(String ctr, MapWidget maps, String precinctNo, String province, String municipality) {
//		this.ctr = ctr;
		this.maps = maps;
		this.precinctNo = precinctNo;
		this.province = province;
		this.municipality = municipality;
		initWidget(uiBinder.createAndBindUi(this));

		precinctNoLabel.setText(precinctNo);
		provinceLabel.setText(province);
		municipalityLabel.setText(municipality);

		initializeMaps();
	}

	private void initializeMaps() {
		maps.addMapClickHandler(new MapClickHandler() {

			@Override
			public void onClick(MapClickEvent event) {
				if (maps.getZoomLevel() < 15) {
					UIUtils.error(errorLabel, ERR_NOT_CLOSE_ENOUGH);
					return;
				}
				if (precinctMarker != null) {
					maps.removeOverlay(precinctMarker);
				}
				precinctMarker = new Marker(event.getLatLng());
				precinctMarker.setDraggingEnabled(true);
				Icon precinctIcon = precinctMarker.getIcon();
				precinctIcon.setImageURL("http://chart.apis.google.com/chart?chst=d_map_xpin_icon&chld=pin_sright|civic-building|C3593C");
				precinctIcon.setShadowURL("http://chart.apis.google.com/chart?chst=d_map_xpin_shadow&chld=pin_sright|civic-building|C3593C");
				precinctIcon.setIconSize(Size.newInstance(23, 33));
				precinctIcon.setShadowSize(Size.newInstance(42, 36));
				precinctIcon.setIconAnchor(Point.newInstance(0, 33));
				maps.addOverlay(precinctMarker);

				infoPanel1.setVisible(false);
				infoPanel2.setVisible(true);
			}

		});
		maps.addMapMoveEndHandler(new MapMoveEndHandler() {
			@Override
			public void onMoveEnd(MapMoveEndEvent event) {
				updateMapsInfo();
			}
		});
		maps.addMapZoomEndHandler(new MapZoomEndHandler() {
			@Override
			public void onZoomEnd(MapZoomEndEvent event) {
				updateMapsInfo();
			}
		});
		updateMapsInfo();
	}

	private void updateMapsInfo() {
		mapCenter = maps.getCenter();
		latBound = (maps.getBounds().getNorthEast().getLatitude()) - maps.getBounds().getSouthWest().getLatitude();
		lngBound = (maps.getBounds().getNorthEast().getLongitude()) - maps.getBounds().getSouthWest().getLongitude();
		mapZoom = maps.getZoomLevel();
	}

	@UiHandler("editAddress")
	void onEditAddress(ClickEvent e) {
//		this.ctr.backEditAddress();
	}

	@UiHandler("mapmakerLink")
	void onMapmakerLink(ClickEvent e) {
		StringBuilder link = new StringBuilder();
		link.append("http://www.google.com/mapmaker?ll=");
		link.append(new Double(mapCenter.getLatitude()).toString().substring(0, 8));
		link.append(",");
		link.append(new Double(mapCenter.getLongitude()).toString().substring(0, 8));
		link.append("&z=");
		link.append(mapZoom);
		link.append("&spn=");
		link.append(latBound);
		link.append(",");
		link.append(lngBound);
		Window.open(link.toString(), "_blank", "");
	}

	@UiHandler("acceptLocation")
	void onAcceptLocation(ClickEvent e) {
		if (finalizingLocation) {
			return;
		}
		finalizingLocation = true;
		acceptLocation.addStyleName(style.disabled());

		PrecinctServiceAsync service = (PrecinctServiceAsync) GWT.create(PrecinctService.class);

//		service.addDraftPrecinctLocation(this.precinctNo,
//				precinctMarker.getLatLng().getLatitude(),
//				precinctMarker.getLatLng().getLongitude(),
//				new AsyncCallback<Void>() {
//
//					@Override
//					public void onSuccess(Void result) {
//						Util.track("/MapYourPrecinct/09-Saved");
//						errorLabel.setText("Your contribution was saved!!  Please contribute some more.  You will be redirected to the main page.");
//						(new Timer() {
//							@Override
//							public void run() {
////								ctr.resetFinderInterface();
//							}
//						}).schedule(4000);
////						acceptLocation.removeStyleName(style.disabled());
////						finalizingLocation = false;
//					}
//
//					@Override
//					public void onFailure(Throwable caught) {
//						UIUtils.error(errorLabel, "Saving of your precinct Location failed.  Please try again later.");
//						acceptLocation.removeStyleName(style.disabled());
//						finalizingLocation = false;
//					}
//				});

	}
}
